package org.jeecg.modules.product.risk.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.product.risk.entity.TbBaseDangerInvestigation;
import org.jeecg.modules.product.risk.entity.TbBaseDangerInvestigationReocrd;
import org.jeecg.modules.product.risk.service.ITbBaseDangerInvestigationReocrdService;
import org.jeecg.modules.product.risk.service.ITbBaseDangerInvestigationService;
import org.jeecg.modules.product.risk.vo.TbBaseDangerInvestigationPage;
import org.jeecg.modules.product.until.BaseRiskCommonConstant;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


/**
 * @Description: 隐患排查信息
 * @Author: jeecg-boot
 * @Date:   2024-05-07
 * @Version: V1.0
 */
@Tag(name="隐患排查信息")
@RestController
@RequestMapping("/TbBaseDangerInvestigation/tbBaseDangerInvestigation")
@Slf4j
public class TbBaseDangerInvestigationController {
	@Autowired
	private ITbBaseDangerInvestigationService tbBaseDangerInvestigationService;
	@Autowired
	private ITbBaseDangerInvestigationReocrdService tbBaseDangerInvestigationReocrdService;

	/**
	 * 分页列表查询
	 *
	 * @param tbBaseDangerInvestigation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "隐患排查信息-分页列表查询")
	@Operation(summary="隐患排查信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TbBaseDangerInvestigation>> queryPageList(TbBaseDangerInvestigation tbBaseDangerInvestigation,
																  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																  HttpServletRequest req) {
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseDangerInvestigation, req.getParameterMap());
		Page<TbBaseDangerInvestigation> page = new Page<TbBaseDangerInvestigation>(pageNo, pageSize);
		queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_0.toString());
		IPage<TbBaseDangerInvestigation> pageList = tbBaseDangerInvestigationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 包保责任隐患分页列表查询
	 *
	 * @param tbBaseDangerInvestigation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@Operation(summary="隐患排查信息-包保责任隐患分页列表查询")
	@GetMapping(value = "/guaranteeLiabilityDangerInvestigationList")
	public Result<IPage<TbBaseDangerInvestigation>> queryPageGuaranteeLiabilityDangerInvestigationList(TbBaseDangerInvestigation tbBaseDangerInvestigation,
																									   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																									   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																									   HttpServletRequest req) {
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseDangerInvestigation, req.getParameterMap());
		Page<TbBaseDangerInvestigation> page = new Page<TbBaseDangerInvestigation>(pageNo, pageSize);
		queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_0.toString());
		queryWrapper.eq("hazard_category", BaseRiskCommonConstant.HAZARD_CATEGORY_GUARANTEELIABILITY.toString());
		IPage<TbBaseDangerInvestigation> pageList = tbBaseDangerInvestigationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询我的排查隐患
	 *
	 * @param tbBaseDangerInvestigation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "隐患排查信息-分页列表查询")
	@Operation(summary="隐患排查信息-分页列表查询我的排查隐患")
	@GetMapping(value = "/myDangerInvestigationList")
	public Result<IPage<TbBaseDangerInvestigation>> queryPageMyDangerInvestigationList(TbBaseDangerInvestigation tbBaseDangerInvestigation,
																					   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																					   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																					   HttpServletRequest req) {
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseDangerInvestigation, req.getParameterMap());
		Page<TbBaseDangerInvestigation> page = new Page<TbBaseDangerInvestigation>(pageNo, pageSize);
		//获取当前用户
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_0.toString());
		queryWrapper.like("liable_person", sysUser.getUsername());
		IPage<TbBaseDangerInvestigation> pageList = tbBaseDangerInvestigationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tbBaseDangerInvestigationPage
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-添加")
	@Operation(summary="隐患排查信息-添加")
	//@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody TbBaseDangerInvestigationPage tbBaseDangerInvestigationPage) {
		TbBaseDangerInvestigation tbBaseDangerInvestigation = new TbBaseDangerInvestigation();
		BeanUtils.copyProperties(tbBaseDangerInvestigationPage, tbBaseDangerInvestigation);
		tbBaseDangerInvestigation.setDeleted(CommonConstant.DEL_FLAG_0.toString());
		tbBaseDangerInvestigationService.saveMain(tbBaseDangerInvestigation, tbBaseDangerInvestigationPage.getTbBaseDangerInvestigationReocrdList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tbBaseDangerInvestigationPage
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-编辑")
	@Operation(summary="隐患排查信息-编辑")
	//@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody TbBaseDangerInvestigationPage tbBaseDangerInvestigationPage) {
		TbBaseDangerInvestigation tbBaseDangerInvestigation = new TbBaseDangerInvestigation();
		BeanUtils.copyProperties(tbBaseDangerInvestigationPage, tbBaseDangerInvestigation);
		TbBaseDangerInvestigation tbBaseDangerInvestigationEntity = tbBaseDangerInvestigationService.getById(tbBaseDangerInvestigation.getId());
		if(tbBaseDangerInvestigationEntity==null) {
			return Result.error("未找到对应数据");
		}
		tbBaseDangerInvestigationService.updateMain(tbBaseDangerInvestigation, tbBaseDangerInvestigationPage.getTbBaseDangerInvestigationReocrdList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-通过id删除")
	@Operation(summary="隐患排查信息-通过id删除")
	//@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		tbBaseDangerInvestigationService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-批量删除")
	@Operation(summary="隐患排查信息-批量删除")
	//@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tbBaseDangerInvestigationService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 *   通过id逻辑删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-通过id逻辑删除")
	@Operation(summary="隐患排查信息-通过id逻辑删除")
	@DeleteMapping(value = "/logicDelete")
	public Result<?> logicDelete(@RequestParam(name="id",required=true) String id) {
		TbBaseDangerInvestigation baseDangerInvestigation = tbBaseDangerInvestigationService.getById(id);
		//禁止状态1是已删除，0是正常未删除
		baseDangerInvestigation.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		tbBaseDangerInvestigationService.updateById(baseDangerInvestigation);
		return Result.OK("逻辑删除成功!");
	}

	/**
	 *  批量逻辑删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "隐患排查信息-批量逻辑删除")
	@Operation(summary="隐患排查信息-批量逻辑删除")
	@DeleteMapping(value = "/deleteLogicBatch")
	public Result<?> deleteLogicBatch(@RequestParam(name="ids",required=true) String ids) {
		List<TbBaseDangerInvestigation> list = tbBaseDangerInvestigationService.listByIds(Arrays.asList(ids.split(",")));
		for (TbBaseDangerInvestigation entity : list) {
			entity.setDeleted(CommonConstant.DEL_FLAG_1.toString());
		}
		tbBaseDangerInvestigationService.updateBatchById(list);
		return Result.OK("批量逻辑删除成功！");
	}

	/**
	 * 获取被逻辑删除
	 *
	 * @return
	 */
	@GetMapping("/recycleBin")
	public Result getRecycleBin() {
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = new QueryWrapper<>();
		//查询已经删除的数据
		QueryWrapper<TbBaseDangerInvestigation> state = queryWrapper.eq("deleted", CommonConstant.DEL_FLAG_1.toString());
		List<TbBaseDangerInvestigation> list = tbBaseDangerInvestigationService.list(queryWrapper);
		return Result.ok(list);
	}

	/**
	 * 还原被逻辑删除
	 *
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
	public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		String ids = jsonObject.getString("ids");
		if (StringUtils.isNotBlank(ids)) {
			List<TbBaseDangerInvestigation> list = tbBaseDangerInvestigationService.listByIds(Arrays.asList(ids.split(",")));
			for (TbBaseDangerInvestigation entity : list) {
				entity.setDeleted(CommonConstant.DEL_FLAG_0.toString());
			}
			tbBaseDangerInvestigationService.updateBatchById(list);
		}
		return Result.ok("还原成功");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "隐患排查信息-通过id查询")
	@Operation(summary="隐患排查信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<TbBaseDangerInvestigation> queryById(@RequestParam(name="id",required=true) String id) {
		TbBaseDangerInvestigation tbBaseDangerInvestigation = tbBaseDangerInvestigationService.getById(id);
		if(tbBaseDangerInvestigation==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(tbBaseDangerInvestigation);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "隐患治理过程信息通过主表ID查询")
	@Operation(summary="隐患治理过程信息主表ID查询")
	@GetMapping(value = "/queryTbBaseDangerInvestigationReocrdByMainId")
	public Result<List<TbBaseDangerInvestigationReocrd>> queryTbBaseDangerInvestigationReocrdListByMainId(@RequestParam(name="id",required=true) String id) {
		List<TbBaseDangerInvestigationReocrd> tbBaseDangerInvestigationReocrdList = tbBaseDangerInvestigationReocrdService.selectByMainId(id);
		return Result.OK(tbBaseDangerInvestigationReocrdList);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param tbBaseDangerInvestigation
	 */
	@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:exportXls")
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TbBaseDangerInvestigation tbBaseDangerInvestigation) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = QueryGenerator.initQueryWrapper(tbBaseDangerInvestigation, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//配置选中数据查询条件
		String selections = request.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		//Step.2 获取导出数据
		List<TbBaseDangerInvestigation> tbBaseDangerInvestigationList = tbBaseDangerInvestigationService.list(queryWrapper);

		// Step.3 组装pageList
		List<TbBaseDangerInvestigationPage> pageList = new ArrayList<TbBaseDangerInvestigationPage>();
		for (TbBaseDangerInvestigation main : tbBaseDangerInvestigationList) {
			TbBaseDangerInvestigationPage vo = new TbBaseDangerInvestigationPage();
			BeanUtils.copyProperties(main, vo);
			List<TbBaseDangerInvestigationReocrd> tbBaseDangerInvestigationReocrdList = tbBaseDangerInvestigationReocrdService.selectByMainId(main.getId());
			vo.setTbBaseDangerInvestigationReocrdList(tbBaseDangerInvestigationReocrdList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "隐患排查信息列表");
		mv.addObject(NormalExcelConstants.CLASS, TbBaseDangerInvestigationPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("隐患排查信息数据", "导出人:"+sysUser.getRealname(), "隐患排查信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("TbBaseDangerInvestigation:tb_base_danger_investigation:importExcel")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TbBaseDangerInvestigationPage> list = ExcelImportUtil.importExcel(file.getInputStream(), TbBaseDangerInvestigationPage.class, params);
				for (TbBaseDangerInvestigationPage page : list) {
					TbBaseDangerInvestigation po = new TbBaseDangerInvestigation();
					BeanUtils.copyProperties(page, po);
					tbBaseDangerInvestigationService.saveMain(po, page.getTbBaseDangerInvestigationReocrdList());
				}
				return Result.OK("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
	}

	/**
	 * 个人隐患查询
	 * @param username
	 * @return
	 */
	//@AutoLog(value = "风险排查记录-个人隐患查询")
	@Operation(summary="隐患排查信息-个人隐患查询")
	@GetMapping(value = "/countDangerInvestigationByUsername")
	public Result<?> countDangerInvestigationByUsername(@RequestParam(name="username") String username,@RequestParam(name="dangerState") String dangerState) {
		QueryWrapper<TbBaseDangerInvestigation> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("liable_person", username);
		queryWrapper.eq("danger_state", dangerState);
		queryWrapper.eq("deleted", "0");
		return Result.OK(tbBaseDangerInvestigationService.list(queryWrapper));
	}

	/**
	 * 本年月累计统计
	 * @return
	 */
	@AutoLog(value = "风险排查记录-本年月累计统计")
	@Operation(summary="隐患排查信息-本年月累计统计")
	@GetMapping(value = "/countForThisYearByMonth")
	public Result<?> countForThisYearByMonth() {
		return Result.OK(tbBaseDangerInvestigationService.countForThisYearByMonth());
	}
}
